package com.michael.leetcode;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.ArrayDeque;
import java.util.Queue;

@Slf4j
public class Connect_116 {

    class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;
        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    };


    public Node connect(Node root) {
        Queue<Node> nodeQueue = new ArrayDeque<Node>();
        nodeQueue.offer(root);

        while (!nodeQueue.isEmpty()){
            int size = nodeQueue.size();
            Node tmp = null;
            for(int i = 0; i < size; i++) {
                Node curr = nodeQueue.poll();
                if (tmp == null){
                    tmp = curr;
                } else {
                    tmp.next = curr;
                    tmp = curr;
                }
                if (curr.left != null){
                    nodeQueue.offer(curr.left);
                }

                if (curr.right != null){
                    nodeQueue.offer(curr.right);
                }
            }
        }
        return root;
    }

    @Test
    public void test(){
        Node n4 = new Node(4);
        Node n5 = new Node(5);
        Node n6 = new Node(6);
        Node n7 = new Node(7);
        Node n2 = new Node(2, n4,n5, null);
        Node n3 = new Node(3,n6, n7, null);
        Node root = new Node(1, n2, n3, null);
        Node connect = connect(root);
        log.info("{}",connect);
    }
}